<template>
  <div class="template-gallery-container">
    <n-card class="gallery-card">
      <template #header>
        <div class="card-header">
          <h1>模板库</h1>
          <n-input-group class="search-box">
            <n-input
              v-model:value="search"
              placeholder="搜索模板..."
              clearable
            />
            <n-button>
              <template #icon><n-icon><SearchOutline /></n-icon></template>
            </n-button>
          </n-input-group>
        </div>
      </template>

      <div class="filter-section">
        <n-space align="center" justify="space-between">
          <n-space>
            <n-select
              v-model:value="filters.category"
              :options="categoryOptions"
              placeholder="类别"
              clearable
              style="width: 120px"
            />
            <n-select
              v-model:value="filters.resolution"
              :options="resolutionOptions"
              placeholder="分辨率"
              clearable
              style="width: 120px"
            />
            <n-select
              v-model:value="filters.sortBy"
              :options="sortOptions"
              placeholder="排序方式"
              style="width: 150px"
            />
          </n-space>

          <n-radio-group v-model:value="viewMode" size="small" style="margin-right: 8px">
            <n-radio-button value="grid">
              <n-icon><GridOutline /></n-icon>
            </n-radio-button>
            <n-radio-button value="list">
              <n-icon><ListOutline /></n-icon>
            </n-radio-button>
          </n-radio-group>
        </n-space>
      </div>

      <div class="template-grid" v-if="viewMode === 'grid'">
        <template v-if="filteredTemplates.length > 0">
          <n-card
            v-for="template in filteredTemplates"
            :key="template.id"
            class="template-card"
            hoverable
            @click="handleTemplateClick(template)"
          >
            <div class="template-preview">
              <img :src="template.thumbnail" :alt="template.name" />
              <div class="template-badge" v-if="template.isPremium">
                <n-tag type="warning" size="small">高级</n-tag>
              </div>
            </div>
            <div class="template-info">
              <h3>{{ template.name }}</h3>
              <p class="template-desc">{{ template.description }}</p>
              <div class="template-meta">
                <span><n-icon><TimeOutline /></n-icon> {{ template.duration }}</span>
                <span><n-icon><ImageOutline /></n-icon> {{ template.resolution }}</span>
              </div>
            </div>
          </n-card>
        </template>
        <n-empty v-else description="没有找到匹配的模板" />
      </div>

      <div class="template-list" v-if="viewMode === 'list'">
        <n-list v-if="filteredTemplates.length > 0">
          <n-list-item v-for="template in filteredTemplates" :key="template.id">
            <n-thing
              :title="template.name"
              :description="template.description"
              @click="handleTemplateClick(template)"
            >
              <template #avatar>
                <img
                  :src="template.thumbnail"
                  :alt="template.name"
                  class="list-thumbnail"
                />
              </template>
              <template #header-extra>
                <n-tag v-if="template.isPremium" type="warning" size="small">高级</n-tag>
              </template>
              <template #description>
                <div class="template-list-desc">
                  <p>{{ template.description }}</p>
                  <div class="template-meta">
                    <span><n-icon><TimeOutline /></n-icon> {{ template.duration }}</span>
                    <span><n-icon><ImageOutline /></n-icon> {{ template.resolution }}</span>
                    <span><n-icon><CalendarOutline /></n-icon> {{ formatDate(template.createdAt) }}</span>
                  </div>
                </div>
              </template>
            </n-thing>
          </n-list-item>
        </n-list>
        <n-empty v-else description="没有找到匹配的模板" />
      </div>

      <div class="pagination-container">
        <n-pagination
          v-model:page="currentPage"
          :page-count="totalPages"
          :page-slot="7"
          :page-sizes="[12, 24, 48]"
          v-model:page-size="pageSize"
          show-quick-jumper
          show-size-picker
          :on-update:page="handlePageChange"
          :on-update:page-size="handlePageSizeChange"
        />
      </div>
    </n-card>

    <!-- 模板详情对话框 -->
    <n-modal
      v-model:show="showTemplateDetails"
      preset="card"
      style="max-width: 800px"
      title="模板详情"
      :bordered="false"
      :segmented="true"
    >
      <template v-if="selectedTemplate">
        <div class="template-detail">
          <div class="template-preview-large">
            <img
              :src="selectedTemplate.thumbnail"
              :alt="selectedTemplate.name"
            />
          </div>

          <div class="template-detail-info">
            <div class="header-with-tag">
              <h2>{{ selectedTemplate.name }}</h2>
              <n-tag v-if="selectedTemplate.isPremium" type="warning">高级模板</n-tag>
            </div>

            <n-divider />

            <p class="detail-description">{{ selectedTemplate.description }}</p>

            <n-descriptions
              label-placement="left"
              bordered
              size="small"
              :column="2"
              class="template-specs"
            >
              <n-descriptions-item label="分辨率">
                {{ selectedTemplate.resolution }}
              </n-descriptions-item>
              <n-descriptions-item label="时长">
                {{ selectedTemplate.duration }}
              </n-descriptions-item>
              <n-descriptions-item label="帧率">
                {{ selectedTemplate.frameRate }} FPS
              </n-descriptions-item>
              <n-descriptions-item label="创建时间">
                {{ formatDate(selectedTemplate.createdAt) }}
              </n-descriptions-item>
              <n-descriptions-item label="类别">
                {{ selectedTemplate.category }}
              </n-descriptions-item>
              <n-descriptions-item label="使用次数">
                {{ selectedTemplate.usageCount }}
              </n-descriptions-item>
            </n-descriptions>

            <div class="tags-section">
              <span class="tags-label">标签：</span>
              <n-space>
                <n-tag
                  v-for="tag in selectedTemplate.tags"
                  :key="tag"
                  size="small"
                  type="info"
                >
                  {{ tag }}
                </n-tag>
              </n-space>
            </div>

            <div class="button-container">
              <n-space justify="end">
                <n-button
                  v-if="selectedTemplate.isPremium && !selectedTemplate.purchased"
                  type="success"
                  @click="handlePurchaseTemplate"
                >
                  <template #icon><n-icon><CartOutline /></n-icon></template>
                  购买模板
                </n-button>
                <n-button
                  type="primary"
                  @click="handleUseTemplate"
                  :disabled="selectedTemplate.isPremium && !selectedTemplate.purchased"
                >
                  <template #icon><n-icon><PlayCircleOutline /></n-icon></template>
                  使用模板
                </n-button>
              </n-space>
            </div>
          </div>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage } from 'naive-ui'
import {
  NCard,
  NButton,
  NInput,
  NInputGroup,
  NIcon,
  NSpace,
  NSelect,
  NRadioGroup,
  NRadioButton,
  NTag,
  NEmpty,
  NList,
  NListItem,
  NThing,
  NDivider,
  NDescriptions,
  NDescriptionsItem,
  NPagination,
  NModal
} from 'naive-ui'
import {
  SearchOutline,
  GridOutline,
  ListOutline,
  TimeOutline,
  ImageOutline,
  CalendarOutline,
  CartOutline,
  PlayCircleOutline
} from '@vicons/ionicons5'
import { useProjectStore } from '../../stores/projectStore'
import { ElectronService } from '../../services/electron.service'

const router = useRouter()
const message = useMessage()
const projectStore = useProjectStore()

// 搜索与筛选状态
const search = ref('')
const viewMode = ref<'grid' | 'list'>('grid')
const filters = reactive({
  category: '' as string,
  resolution: '' as string,
  sortBy: 'newest'
})

// 分页
const currentPage = ref(1)
const pageSize = ref(12)
const totalPages = ref(1)

// 选中的模板
const showTemplateDetails = ref(false)
const selectedTemplate = ref<Template | null>(null)

// 模板数据类型
interface Template {
  id: string
  name: string
  description: string
  thumbnail: string
  category: string
  tags: string[]
  resolution: string
  duration: string
  frameRate: number
  createdAt: string
  isPremium: boolean
  purchased: boolean
  usageCount: number
}

// 模拟模板数据
const templates = ref<Template[]>([])

// 筛选选项
const categoryOptions = [
  { label: '全部', value: '' },
  { label: '商业演示', value: 'business' },
  { label: '个人vlog', value: 'vlog' },
  { label: '节日庆典', value: 'holiday' },
  { label: '社交媒体', value: 'social' },
  { label: '教育培训', value: 'education' }
]

const resolutionOptions = [
  { label: '全部', value: '' },
  { label: '720p', value: '1280x720' },
  { label: '1080p', value: '1920x1080' },
  { label: '4K', value: '3840x2160' },
  { label: '方形', value: '1080x1080' },
  { label: '竖屏', value: '1080x1920' }
]

const sortOptions = [
  { label: '最新发布', value: 'newest' },
  { label: '最多使用', value: 'popular' },
  { label: '名称 A-Z', value: 'nameAsc' },
  { label: '名称 Z-A', value: 'nameDesc' }
]

// 获取筛选后的模板列表
const filteredTemplates = computed(() => {
  let result = [...templates.value]
  
  // 搜索筛选
  if (search.value) {
    const searchLower = search.value.toLowerCase()
    result = result.filter(
      template => template.name.toLowerCase().includes(searchLower) || 
                  template.description.toLowerCase().includes(searchLower) ||
                  template.tags.some(tag => tag.toLowerCase().includes(searchLower))
    )
  }
  
  // 类别筛选
  if (filters.category) {
    result = result.filter(template => template.category === filters.category)
  }
  
  // 分辨率筛选
  if (filters.resolution) {
    result = result.filter(template => template.resolution === filters.resolution)
  }
  
  // 排序
  switch (filters.sortBy) {
    case 'newest':
      result.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
      break
    case 'popular':
      result.sort((a, b) => b.usageCount - a.usageCount)
      break
    case 'nameAsc':
      result.sort((a, b) => a.name.localeCompare(b.name))
      break
    case 'nameDesc':
      result.sort((a, b) => b.name.localeCompare(a.name))
      break
  }
  
  // 计算总页数
  totalPages.value = Math.ceil(result.length / pageSize.value)
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
}

// 加载模板数据
const loadTemplates = async () => {
  try {
    // 实际项目中应该调用 API 获取模板数据
    // const response = await ElectronService.getTemplates()
    // if (response.success) {
    //   templates.value = response.templates
    // }
    
    // 模拟数据
    templates.value = generateMockTemplates()
  } catch (error) {
    console.error('加载模板失败:', error)
    message.error('加载模板时发生错误')
  }
}

// 生成模拟数据
const generateMockTemplates = (): Template[] => {
  const mockTemplates: Template[] = []
  const categories = ['business', 'vlog', 'holiday', 'social', 'education']
  const resolutions = ['1280x720', '1920x1080', '3840x2160', '1080x1080', '1080x1920']
  const durations = ['00:30', '01:00', '01:30', '02:00', '02:30', '03:00']
  
  // 生成30个模拟模板
  for (let i = 1; i <= 30; i++) {
    const category = categories[Math.floor(Math.random() * categories.length)]
    const resolution = resolutions[Math.floor(Math.random() * resolutions.length)]
    const isPremium = Math.random() > 0.7
    
    mockTemplates.push({
      id: `template-${i}`,
      name: `模板 ${i} - ${category.charAt(0).toUpperCase() + category.slice(1)}`,
      description: `这是一个${isPremium ? '高级' : '免费'}的${category}类型模板，适用于各种场景。`,
      thumbnail: `https://picsum.photos/id/${Math.floor(Math.random() * 100)}/300/200`,
      category,
      tags: ['动画', '过渡', '文字', '特效'].slice(0, Math.floor(Math.random() * 4) + 1),
      resolution,
      duration: durations[Math.floor(Math.random() * durations.length)],
      frameRate: [24, 30, 60][Math.floor(Math.random() * 3)],
      createdAt: new Date(Date.now() - Math.floor(Math.random() * 10000000000)).toISOString(),
      isPremium,
      purchased: isPremium ? Math.random() > 0.5 : true,
      usageCount: Math.floor(Math.random() * 1000)
    })
  }
  
  return mockTemplates
}

// 处理模板点击事件
const handleTemplateClick = (template: Template) => {
  selectedTemplate.value = template
  showTemplateDetails.value = true
}

// 使用模板创建项目
const handleUseTemplate = async () => {
  if (!selectedTemplate.value) return
  
  if (selectedTemplate.value.isPremium && !selectedTemplate.value.purchased) {
    message.warning('请先购买该模板')
    return
  }
  
  try {
    message.success('正在创建新项目...')
    
    // 这里应该调用创建项目的 API
    // const result = await projectStore.createProject({
    //   name: `基于 ${selectedTemplate.value.name} 的项目`,
    //   templateId: selectedTemplate.value.id,
    //   // 其他项目属性
    // })
    
    // 模拟创建项目成功
    setTimeout(() => {
      // 关闭模态框
      showTemplateDetails.value = false
      
      // 跳转到编辑器页面
      router.push('/editor/project-new')
    }, 1000)
  } catch (error) {
    console.error('创建项目失败:', error)
    message.error('创建项目时发生错误')
  }
}

// 购买模板
const handlePurchaseTemplate = () => {
  if (!selectedTemplate.value) return
  
  message.info('购买功能开发中...')
  // 实际项目中应该调用购买 API
  // 成功后更新模板的购买状态
  // selectedTemplate.value.purchased = true
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
}

const handlePageSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1 // 重置到第一页
}

// 初始化
onMounted(() => {
  loadTemplates()
})
</script>

<style lang="scss" scoped>
.template-gallery-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  
  .gallery-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      flex-wrap: wrap;
      gap: 16px;
      
      h1 {
        margin: 0;
        font-size: 24px;
        font-weight: 500;
      }
      
      .search-box {
        width: 300px;
      }
    }
  }
  
  .filter-section {
    margin: 16px 0;
    padding-bottom: 16px;
    border-bottom: 1px solid var(--border-color);
  }
  
  .template-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 20px;
    margin-top: 20px;
    
    .template-card {
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
      }
      
      .template-preview {
        position: relative;
        height: 160px;
        overflow: hidden;
        border-radius: 3px;
        background-color: var(--card-color);
        
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.3s;
        }
        
        &:hover img {
          transform: scale(1.05);
        }
        
        .template-badge {
          position: absolute;
          top: 8px;
          right: 8px;
        }
      }
      
      .template-info {
        padding: 12px 8px 8px;
        
        h3 {
          margin: 0 0 8px;
          font-size: 16px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        
        .template-desc {
          font-size: 14px;
          color: var(--text-color-secondary);
          margin: 0 0 12px;
          height: 40px;
          overflow: hidden;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .template-meta {
          display: flex;
          justify-content: space-between;
          font-size: 12px;
          color: var(--text-color-secondary);
          
          span {
            display: flex;
            align-items: center;
            gap: 4px;
          }
        }
      }
    }
  }
  
  .template-list {
    margin-top: 20px;
    
    .list-thumbnail {
      width: 120px;
      height: 80px;
      object-fit: cover;
      border-radius: 3px;
    }
    
    .template-list-desc {
      .template-meta {
        display: flex;
        gap: 16px;
        margin-top: 8px;
        font-size: 12px;
        color: var(--text-color-secondary);
        
        span {
          display: flex;
          align-items: center;
          gap: 4px;
        }
      }
    }
  }
  
  .pagination-container {
    margin-top: 32px;
    display: flex;
    justify-content: center;
  }
  
  // 模板详情样式
  .template-detail {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24px;
    
    .template-preview-large {
      width: 100%;
      
      img {
        width: 100%;
        height: auto;
        border-radius: 4px;
      }
    }
    
    .template-detail-info {
      .header-with-tag {
        display: flex;
        align-items: center;
        gap: 12px;
        margin-bottom: 8px;
        
        h2 {
          margin: 0;
        }
      }
      
      .detail-description {
        margin-bottom: 20px;
        color: var(--text-color-secondary);
      }
      
      .template-specs {
        margin-bottom: 20px;
      }
      
      .tags-section {
        margin-bottom: 24px;
        
        .tags-label {
          color: var(--text-color-secondary);
          margin-right: 8px;
        }
      }
      
      .button-container {
        margin-top: 20px;
      }
    }
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .template-gallery-container {
    padding: 10px;
    
    .gallery-card .card-header {
      flex-direction: column;
      align-items: stretch;
      
      .search-box {
        width: 100%;
      }
    }
    
    .template-detail {
      grid-template-columns: 1fr;
    }
  }
}
</style> 